﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections;
using System.Diagnostics;
using PClusterModel.Utils;

namespace PClusterModel.Infrastructure
{
    [DebuggerDisplay("{owner.Name} - {maximalDimensionSets.Count}")]
    public class Block
    {
        private IMicroarrayDataObject owner;
        private List<MaximalDimensionBlockSet> maximalDimensionSets;

        public Block(IMicroarrayDataObject owner)
        {
            this.owner = owner;
            this.maximalDimensionSets = new List<MaximalDimensionBlockSet>();
        }

        public IMicroarrayDataObject Owner
        {
            get { return owner; }
        }

        public List<MaximalDimensionBlockSet> MaximalDimensionSets
        {
            get { return maximalDimensionSets; }
        }

        public int GetMDSCountForCondition(int conditionIndex)
        {
            int objectPairsCountForColumn = 0;
            foreach (MaximalDimensionBlockSet mds in this.MaximalDimensionSets)
            {
                foreach (BitArray bitmap in mds.ConditionBitMaps)
                {
                    if (bitmap[conditionIndex])
                    {
                        objectPairsCountForColumn++;
                        break;
                    }
                }
            }
            return objectPairsCountForColumn;
        }

        public MaximalDimensionBlockSet GetMaximalDimensionSetWithObject(IMicroarrayDataObject pairedObject)
        {
            foreach (MaximalDimensionBlockSet mds in this.maximalDimensionSets)
            {
                if (mds.FirstMicroarrayObject.Equals(pairedObject) || mds.SecondMicroarrayObject.Equals(pairedObject))
                {
                    return mds;
                }
            }
            return null;
        }

        public List<IMicroarrayDataObject> GetDataObjectsClusteredOnConditionSet(BitArray clusteringBitmap)
        {
            List<IMicroarrayDataObject> objects = new List<IMicroarrayDataObject>() { this.owner };
            foreach (MaximalDimensionBlockSet mds in this.MaximalDimensionSets)
            {
                foreach (BitArray bitmap in mds.ConditionBitMaps)
                {
                    if (Utilities.IsBitmapSubsetOfSecondBitmap(clusteringBitmap, bitmap))
                    {
                        IMicroarrayDataObject second = mds.FirstMicroarrayObject.Equals(this.owner) ? mds.SecondMicroarrayObject : mds.FirstMicroarrayObject;
                        objects.Add(second);
                        break;
                    }
                }
            }
            return objects;
        }

    }
}
